import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { Child } from '../../entities/Child.entity'
import { UserChild } from '../../entities/UserChild.entity'

@Provide()
export class ChildService {
  @InjectEntityModel(Child)
  repo!: Repository<Child>

  @InjectEntityModel(UserChild)
  userChildRepo!: Repository<UserChild>

  async list(page: number = 1, pageSize: number = 10) {
    const [data, total] = await this.repo.findAndCount({
      skip: (page - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' } // 可选排序
    })

    return {
      total,
      items: data,
    }
  }

  async add(data: Partial<Child> & { userId?: string; relationType?: number }) {
    const { userId, relationType, ...childData } = data
    
    // 创建并保存孩子信息
    const obj = this.repo.create(childData)
    const savedChild = await this.repo.save(obj)
    
    // 如果传入了用户ID，则创建用户-孩子关联
    if (userId) {
      const userChild = this.userChildRepo.create({
        userId,
        childId: savedChild.id,
        relationType: relationType || 3, // 默认为监护人
      })
      await this.userChildRepo.save(userChild)
    }
    
    return savedChild
  }

  async edit(data: Partial<Child> & { userId?: string; relationType?: number }) {
    const { userId, relationType, ...childData } = data
    
    // 更新孩子信息
    const savedChild = await this.repo.save(childData)
    
    // 如果传入了用户ID，则创建或更新用户-孩子关联
    if (userId && childData.id) {
      // 检查是否已存在关联
      const existingRelation = await this.userChildRepo.findOne({
        where: {
          userId,
          childId: childData.id,
        },
      })
      
      if (existingRelation) {
        // 更新关系类型
        if (relationType) {
          existingRelation.relationType = relationType
          await this.userChildRepo.save(existingRelation)
        }
      } else {
        // 创建新关联
        const userChild = this.userChildRepo.create({
          userId,
          childId: childData.id,
          relationType: relationType || 3,
        })
        await this.userChildRepo.save(userChild)
      }
    }
    
    return savedChild
  }

  async delete(id: number) {
    return this.repo.delete(id)
  }
}
